package com.atstudent.gmall.common.feign.util;

import com.atstudent.gmall.common.feign.interceptor.AuthUserInfo;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author 薛有朋
 * @CreatDate 2025/4/15 21:08
 * ThreadLocal: 在同一个线程中进行数据的共享
 * RequestContextHolder底层原理：
 * 1、监听器
 * 2、ThreadLocal
 * 通过监听器监听Request对象的变化，当Request对象创建好了以后，那么此时就会把request对象存储到RequestContextHolder对象的ThreadLocal属性上
 **/
public class AuthUserInfoUtils {

    public static AuthUserInfo getAuthUserInfo(){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null){
            HttpServletRequest httpServletRequest = requestAttributes.getRequest();
            String userId = httpServletRequest.getHeader("userId");
            String userTempId = httpServletRequest.getHeader("userTempId");
            AuthUserInfo authUserInfo = new AuthUserInfo();
            authUserInfo.setUserId(userId);
            authUserInfo.setUserTempId(userTempId);
            return authUserInfo;
        }
        return null;
    }
}
